<?php

/**
 * 首页.
 * 
 * @author aic <41262633@qq.com>
 */

namespace Controller;

/**
 * Class Controller Index.
 */
class Index extends \Controller\Base {

    public function __construct($vals = array()) {
        parent::__construct($vals);
    }

    /**
     * 首页
     */
    public function index() {
        header("Location: /my");
    }

    /**
     * 热卖清单
     */
    public function hot() {
        $page = $this->getGet('page');
        $page = $page ? $page : 1;
        $ajax = $this->getGet('ajax');
        $more = $this->getGet('more');

        // 默认最低红包2元
        $minPacket = 2;
        // 默认最低销量3333
        $minVolume = 3333;

        if ($more) {
            $minPacket = 1;
        }

        $limit = 20;
        $where = "`red_packet` >= '$minPacket' and `volume` >= '$minVolume'";
        $order = "`id` desc";

        $result = \Logic\Product::getProductList($where, $order, $limit, $page, $more, 'hot');

        $this->assign('result', $result);
        $this->assign('title', '热卖清单');
        $this->assign('type', 'you');
        $this->assign('burl', '/index/hot?');
        $this->assign('tab_type', 'hot');

        if ($ajax) {
            $return = $this->display('tao/list_content_tpl', true);
            echo $return;
            exit;
        }
        $this->display('tao/list_you');
    }

    /**
     * 淘宝推荐
     */
    public function tui() {
        $page = $this->getGet('page');
        $page = $page ? $page : 1;
        $ajax = $this->getGet('ajax');
        $more = $this->getGet('more');

        // 默认最低红包2元
        $minPacket = 2;

        if ($more) {
            $minPacket = 1;
        }

        $where = "`status`= '2' and `red_packet` >= '$minPacket' and `amount` > 0";
        $limit = 20;
        $order = "`id` desc";

        $result = \Logic\Product::getProductList($where, $order, $limit, $page, $more, 'tui');

        $this->assign('result', $result);
        $this->assign('title', '淘宝推荐');
        $this->assign('type', 'you');
        $this->assign('burl', '/index/tui?');
        $this->assign('tab_type', 'tui');

        if ($ajax) {
            $return = $this->display('tao/list_content_tpl', true);
            echo $return;
            exit;
        }

        $this->display('tao/list_you');
    }

    /**
     * 商城正品
     */
    public function mall() {
        $page = $this->getGet('page');
        $page = $page ? $page : 1;
        $ajax = $this->getGet('ajax');
        $more = $this->getGet('more');

        // 默认最低红包2元
        $minPacket = 2;

        if ($more) {
            $minPacket = 1;
        }

        $where = "`red_packet` >= '$minPacket' and `user_type`='1'";
        $limit = 20;
        $order = "`id` desc";

        $result = \Logic\Product::getProductList($where, $order, $limit, $page, $more, 'mall');

        $this->assign('result', $result);
        $this->assign('title', '商城正品');
        $this->assign('type', 'you');
        $this->assign('burl', '/index/mall?');
        $this->assign('tab_type', 'mall');

        if ($ajax) {
            $return = $this->display('tao/list_content_tpl', true);
            echo $return;
            exit;
        }

        $this->display('tao/list_you');
    }

    /**
     * 搜索查询
     */
    public function search() {
        $q = $this->getGet('q');
        $page = $this->getGet('page');
        $page = $page ? $page : 1;
        $ajax = $this->getGet('ajax');

        if (empty($q)) {

            $co = $this->getGet('co');
            \Logic\Product::itemGoToWx('search', '', '', $this->role, $co);

            $this->assign('type', 'search');
            $this->assign('tab_type', 'search');
            $this->display('index/search');
            return;
        }

        $r = new \Logic\Search($q, $page);
        $result = $r->query();
        $burl = "search?q={$q}&";

        $this->assign('result', $result);
        $this->assign('title', '搜索: ' . $result['title']);
        $this->assign('type', 'search');
        $this->assign('burl', $burl);

        if ($ajax) {
            $return = $this->display('tao/list_content_tpl', true);
            echo $return;
            exit;
        }
        $this->display('tao/list');
    }

    /**
     * 搜券
     */
    public function soq() {
        $q = $this->getGet('q');
        $page = $this->getGet('page');
        $page = $page ? $page : 1;
        $ajax = $this->getGet('ajax');

        if (empty($q)) {
            $this->assign('type', 'search');
            $this->assign('tab_type', 'search');
            $this->display('index/soq');
            return;
        }

        $r = new \Logic\Search($q, $page, false);
        $result = $r->query();
        $burl = "/index/soq?q={$q}&";

        $this->assign('result', $result);
        $this->assign('title', '搜索: ' . $result['title']);
        $this->assign('type', 'search');
        $this->assign('burl', $burl);

        if ($ajax) {
            $return = $this->display('tao/list_content_filter', true);
            echo $return;
            exit;
        }
        $this->display('tao/list_filter');
    }

    /**
     * 分享页
     */
    public function share() {
        $product_id = $this->param['productId'];
        if (!$product_id) {
            exit('商品id无效');
        }

        $e = $this->getGet('e');

        $info = \Logic\Product::getItemInfo($product_id, $e, 'share');
        $this->assign('info', $info);
        $this->display('tao/share');
    }

    /**
     * 商品详情页
     */
    public function item() {
        $product_id = $this->param['productId'];
        if (!$product_id) {
            exit('商品id无效');
        }

        $e = $this->getGet('e');
        $co = $this->getGet('co');
        $vid = $this->getGet('vid');

        if ($vid) {
            \Common::setCookie('inviteid', $vid);
        }

        // 是否跳转到微信授权页
        \Logic\Product::itemGoToWx('item', $product_id, $e, $this->role, $co, '', $vid);

        $info = \Logic\Product::getItemInfo($product_id, $e, 'item');
        $this->assign('info', $info);
        $this->assign('type', 'bao');
        $this->display('tao/item');
    }

    /**
     * 中间跳转页面
     */
    public function itemgo() {
        // 获取微信账号信息
        $code = $this->getGet('code');
        $access_token = '';
        $openid = '';

        // 邀请者信息
        $inviteid = \Common::getCookie('inviteid');
        $getinviteid = $this->getGet('getinviteid');
        $inviteid = $getinviteid ? $getinviteid : $inviteid;

        $inviter = [];
        if ($inviteid) {
            $inviter = \Db::instance()->getRow("select `id` from `wx_user` where `openid`='$inviteid'");
        }

        // 获取access_token
        while ($code) {
            $apiUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token?'
                    . 'appid=' . \Config\System::$site['wx']['appId']
                    . '&secret=' . \Config\System::$site['wx']['appSecret']
                    . '&code=' . $code
                    . '&grant_type=authorization_code';

            $result = file_get_contents($apiUrl);
            if (!$result) {
                break;
            }

            $t = json_decode($result, true);
            if (!$t || !isset($t['access_token']) || !isset($t['openid']) || !$t['openid']) {
                break;
            }

            $access_token = $t['access_token'];
            $openid = $t['openid'];
            \Common::setCookie('openid', $openid, 31104000);
            break;
        }

        // 获取wx_user_info
        $uinfo = [];
        while ($access_token && $openid) {
            $apiUrl = 'https://api.weixin.qq.com/sns/userinfo?'
                    . 'access_token=' . $access_token
                    . '&openid=' . $openid
                    . '&lang=zh_CN';

            $result = file_get_contents($apiUrl);
            if (!$result) {
                break;
            }

            $t = json_decode($result, true);
            if (!$t || !isset($t['nickname'])) {
                break;
            }

            $uinfo = $t;
            break;
        }

        if ($openid) {
            // 数据更新param
            $param = [
                'openid' => $openid,
                'nickname' => isset($uinfo['nickname']) ? $uinfo['nickname'] : '',
                'sex' => isset($uinfo['sex']) ? $uinfo['sex'] : '',
                'headimgurl' => isset($uinfo['headimgurl']) ? $uinfo['headimgurl'] : '',
            ];

            $row = \Db::instance()->getRow("select `id`,`inviter`,`invittime` from `wx_user` where `openid`='$openid'");
            if (!$row) {
                // 新增会员
                if ($inviter && $inviteid != $openid) {
                    // 邀请者
                    $param['inviter'] = $inviteid;
                    $param['invittime'] = time();
                }

                $ret = \Db::instance()->insert('wx_user', $param);
                if ($ret && $inviteid) {
                    \Common::setCookie('inviteid', '', -100);
                }
            }

            if ($row && $uinfo) {
                if ($inviter && !$row['inviter'] && $inviteid != $openid) {
                    $param['inviter'] = $inviteid;
                }
                if ($inviter && !$row['invittime'] && $inviteid != $openid) {
                    $param['invittime'] = time();
                }
                $ret = \Db::instance()->updateByWhere('wx_user', $param, "openid='$openid'");
                if ($ret !== false && $inviteid) {
                    \Common::setCookie('inviteid', '', -100);
                }
            }
        }

        $last_item = \Common::getCookie('last_item');
        if (!$last_item) {
            $last_item = 'my?';
        }

        $last_url = \Config\System::$site['host'] . $last_item . '&co=wx';
        \Common::redirect($last_url);
    }

    /**
     * user_item点击关系
     */
    public function useritem() {
        $openid = $this->openid;
        if (!$openid) {
            exit;
        }

        $product_id = $this->getGet('product_id');
        if (!$product_id) {
            exit;
        }

        $param = [
            'openid' => $openid,
            'product_id' => $product_id,
        ];

        if (\Db::instance()->count("select count(1) from `user_item` where `openid`='$openid' and `product_id`='$product_id'")) {
            $param['update_time'] = time();
            $ret = \Db::instance()->updateByWhere('user_item', $param, "`openid`='$openid' and `product_id`='$product_id'");
        } else {
            $param['create_time'] = $param['update_time'] = time();
            $ret = \Db::instance()->insert('user_item', $param);
        }

        exit;
    }

    /**
     * 邀请有奖
     */
    public function invite() {
        $co = $this->getGet('co');

        // 是否跳转到微信授权页
        \Logic\Product::itemGoToWx('invite', 0, '', $this->role, $co);

        $openid = \Common::getCookie('openid');
        $uinfo = [];
        if ($openid) {
            $uinfo = \Db::instance()->getRow("select `id`,`openid` from `wx_user` where `openid`='$openid'");
        }
        $shorturl = '';

        if ($uinfo) {
            $url = \Config\System::$site['host'] . 'my?inviteid=' . $openid;
            $shorturl = \Common::getShortUrl($url);
        }

        $this->assign('shorturl', $shorturl);
        $this->assign('type', 'invite');
        $this->display('index/invite');
    }

    /**
     * 红包统计
     */
    public function tongji() {
        // 总计红包
        $tj = [];

        if (file_exists(CACHE_PATH . 'tongji/tj.cache')) {
            $ret = file_get_contents(CACHE_PATH . 'tongji/tj.cache');
            if ($ret) {
                $arr = json_decode($ret, true);
                $tj = $arr ? $arr : [];
            }
        }

        $this->assign('tj', $tj);
        $this->assign('tab_type', 'pr');

        // 近期发放红包
        $order = '`packet_time` desc';
        $where = "`total_packet` > 1 and `status` = '6'";
        $resp = \Logic\ORC::orderGet($where, 1, $order);
        $this->assign('data_list', $resp['data_list']);
        $this->display('index/tongji');
    }

    /**
     * 红包榜
     */
    public function packettop() {
        $type = $this->getGet('type');
        $type = $type ? $type : 'all';

        $dataList = [];

        if ($type == 'all') {
            // 红包总榜
            $ret = file_get_contents(CACHE_PATH . 'tongji/packetTopAll.cache');
            $dataList = $ret ? json_decode($ret, true) : [];
            $this->assign('tab_type', 'pa');
        }

        if ($type == 'mon') {
            // 红包月榜
            $ret = file_get_contents(CACHE_PATH . 'tongji/packetTopMon.cache');
            $dataList = $ret ? json_decode($ret, true) : [];
            $this->assign('tab_type', 'pm');
        }

        $this->assign('dataList', $dataList);
        $this->display('index/packettop');
    }

    /**
     * 2018双11天猫全球狂欢节
     */
    public function tianmao() {
        // 判断是否去微信授权页
        $co = $this->getGet('co');
        \Logic\Product::itemGoToWx('taobao', 0, '', $this->role, $co, 'index/tianmao');
        $this->display('index/tianmao');
    }

}
